/**
 * 
 */
package com.jml.springsecurity.core.social.qq.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

//这是一个多实例的类
//第六步，所有的api都继承AbstractOAuth2ApiBinding
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {
	//得到openid的请求路径
	private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";
	//获取用户信息的路径
	private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";
	//accessToken回由SpringSocial返给我们，其他的我们自己获取

	//自己的在qq互联上注册成功后，系统给的，可以通过appId获取openId
	private String appId;
	//用户ID，通过请求获取的
	private String openId;

	private ObjectMapper objectMapper = new ObjectMapper();

	//accessToken就是走完前5步获取的令牌Token，该构造获取openId
	public QQImpl(String accessToken, String appId) {
		//父类的这个会自动处理token放在请求中
		super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
		this.appId = appId;
		//将access token放入链接中替换%s
		String url = String.format(URL_GET_OPENID, accessToken);
		//发送http请求得到openId
		String result = getRestTemplate().getForObject(url, String.class);
		System.out.println(result);
		//从返回的内容中截取openID
		this.openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");
	}
	
	@Override
	public QQUserInfo getUserInfo() {
		String url = String.format(URL_GET_USERINFO, appId, openId);
		//发送请求，获取对象
		String result = getRestTemplate().getForObject(url, String.class);
		System.out.println(result);
		QQUserInfo userInfo = null;
		try {
			userInfo = objectMapper.readValue(result, QQUserInfo.class);
			userInfo.setOpenId(openId);
			return userInfo;
		} catch (Exception e) {
			throw new RuntimeException("获取用户信息失败", e);
		}
	}
}
